package xyz.mumuwei.youthcourseserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.mumuwei.youthcourseserver.common.dto.PageDto;
import xyz.mumuwei.youthcourseserver.common.lang.Result;
import xyz.mumuwei.youthcourseserver.mapper.EvaluateMapper;
import xyz.mumuwei.youthcourseserver.pojo.CourseEvaluate;
import xyz.mumuwei.youthcourseserver.service.CourseEvaluateService;

import java.util.List;


/**
 * @author mumuwei
 * @since 2022-02-19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseEvaluateServiceImpl extends ServiceImpl<EvaluateMapper, CourseEvaluate> implements CourseEvaluateService {

    final EvaluateMapper evaluateMapper;

    /**
     * 根据课程id查询课程评价列表
     *
     * @param courseId 课程id
     * @return 评价列表
     */
    @Override
    public Result getListByCourseId(Integer courseId) {
        return Result.success(evaluateMapper.getListByCourseId(courseId));
    }

    /**
     * 根据课程id查询课程评价列表(分页)
     *
     * @param courseId 课程id
     * @param pageDto  分页信息
     * @return 评论列表
     */
    @Override
    public Result getPageByCourseId(Integer courseId, PageDto pageDto) {
        pageDto.setStart((pageDto.getCurrent()-1)*pageDto.getSize());
        pageDto.setEnd(pageDto.getCurrent()*pageDto.getSize());
        pageDto.setId(courseId);
        List<CourseEvaluate> page = evaluateMapper.getPageByCourseId(pageDto);
        Page<CourseEvaluate> evaluatePage = new Page<>(pageDto.getCurrent(), pageDto.getSize());
        evaluatePage.setRecords(page);
        if (page.size() <= 0) {
            evaluatePage.setTotal(0);
            return Result.success(evaluatePage);
        }
        if(!"".equals(pageDto.getKey())) {
            evaluatePage.setTotal(evaluateMapper.selectCount(new QueryWrapper<CourseEvaluate>()
                    .eq("course_id", courseId)
                    .like("text", pageDto.getKey())
            ));
        } else {
            evaluatePage.setTotal(evaluateMapper.selectCount(new QueryWrapper<CourseEvaluate>().eq("course_id", courseId)));
        }
        return Result.success(evaluatePage);
    }

    /**
     * 获取课程质量
     *
     * @return 数据
     */
    @Override
    public Result getCourseQuality() {
        return Result.success(evaluateMapper.getCourseQuality());
    }
}
